<?php
/**
 *      [Haidao] (C)2013-2099 Dmibox Science and technology co., LTD.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      http://www.haidao.la
 *      tel:400-600-2042
 */
class admin_logic extends logic{
    public function __construct() {
        $this->model = model('admin_user', 'table');
        
    }
    
    public function login($username, $password) {
        if(empty($username)) {
            $this->error = '用户名不能为空';
            return FALSE;
        }
        if(empty($password)) {
            $this->error = '密码不能为空';
            return FALSE;
        }
        $admin_user = $this->model->fetch_by_username($username);
        if(!$admin_user) {
            $this->error = '账号不存在';
            return FALSE;
        }
        if($admin_user['password'] !== $this->_create_password($password, $admin_user['encrypt'])) {
            $this->error = '登陆密码验证失败';
            return FALSE;
        }
        $this->admin_user = $admin_user;
        return $this->_dologin($admin_user['id']);
    }
    
    /**
     * 生成登陆密码
     * @param string $pwd 原始密码
     * @param string $encrypt 混淆字符
     * @return string
     */
    public function _create_password($pwd, $encrypt = '') {
        if(empty($encrypt)) $encrypt = random (6);
        return md5($pwd.$encrypt);
    }
    
    
    private function _dologin($id) {		
        $auth = authcode($id."\t".  random(6), 'ENCODE');
		$this->model->where(array('id'=>$id))->save(array('last_login_time'=>time(),'login_num'=>array('exp','`login_num`+1')));
        session('authkey', $auth);
        return TRUE;
    }
	/**
     * 密码是否正确
     * @password  原始密码
     * @return bool
     */
	public function check_password($password){
		if(!$password){
			$this->error = '原密码必须填写';
			return false;
		}
		$admin_user = $this->model->fetch_by_id(ADMIN_ID);
		if($admin_user['password'] !==  $this->_create_password($password, $admin_user['encrypt'])){
			$this->error = '原密码不正确，请重新填写';
			return false;
		}
		return true;
	}
	/**
     * 修改管理员资料
	 * @params array 用户资料
     * @return bool
     */
	public function update($params = array()){
		if(empty($params['newpassword'])) return true;
		if(!$this->check_password($params['oldpassword'])) return false;
		if($params['newpassword'] !== $params['pwpassword']){
			$this->error = '两次输入的密码不一致';
			return false;
		}
		$data = array();
		$data['id'] = ADMIN_ID;
		$data['encrypt'] = random(10);
		$data['password'] = create_password($params['newpassword'], $data['encrypt']);
		$data['username'] = $this->model->where(array('id'=>ADMIN_ID))->getField('username');
		$result = $this->model->update($data);
		if($result === FALSE){
			$this->error = $this->model->getError();
			return false;
		}
		return true;
	}
}
